package com.wang.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.myblog.entity.Navbar;
import com.wang.myblog.entity.dto.NavbarDto;
import com.wang.myblog.mapper.NavbarMapper;
import com.wang.myblog.service.NavbarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author s
 * @since 2021-05-21
 */
@Service
public class NavbarServiceImpl extends ServiceImpl<NavbarMapper, Navbar> implements NavbarService {

    @Override
    public List<NavbarDto> treeList() {
        QueryWrapper<Navbar> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("sort");
        List<Navbar> navbarList = baseMapper.selectList(wrapper);
        return navbarList.stream().filter((entity) -> {
            return entity.getLv() == 1;//等级为1
        }).map((root) -> {
            NavbarDto navbarDto = new NavbarDto();
            BeanUtils.copyProperties(root, navbarDto);
            List<NavbarDto> children = getChildren(root, navbarList);
            navbarDto.setChildren(children);
            return navbarDto;
        }).collect(Collectors.toList());
    }

    /**
     * 获取子菜单树
     *
     * @param root
     * @param allList
     * @return
     */
    private List<NavbarDto> getChildren(Navbar root, List<Navbar> allList) {
        return allList.stream().filter((entity) -> {
            return root.getId().equals(entity.getPid());//对应关系
        }).map((menu) -> {
            NavbarDto navbarDto = new NavbarDto();
            BeanUtils.copyProperties(menu, navbarDto);
            List<NavbarDto> children = getChildren(menu, allList);
            navbarDto.setChildren(children);
            return navbarDto;
        }).collect(Collectors.toList());
    }

}
